<template>
  <div class="basic-info-section">
    <!-- 模块标题 -->
    <div class="section-header">
      <div class="header-left">
        <el-icon class="section-icon"><User /></el-icon>
        <h3 class="section-title">基础信息</h3>
        <el-tag v-if="completionPercentage < 100" type="warning" size="small">
          完成度 {{ completionPercentage }}%
        </el-tag>
        <el-tag v-else type="success" size="small">
          <el-icon><CircleCheck /></el-icon>
          已完成
        </el-tag>
      </div>
      <div class="header-right">
        <el-button 
          v-if="hasErrors" 
          type="danger" 
          text 
          size="small"
          @click="scrollToFirstError"
        >
          <el-icon><Warning /></el-icon>
          {{ validationErrors.length }} 项需要修正
        </el-button>
      </div>
    </div>

    <!-- 基础信息表单 -->
    <div class="section-content">
      <!-- 个人基本信息区块 -->
      <div class="info-block">
        <div class="block-title">
          <el-icon><CreditCard /></el-icon>
          <span>个人基本信息</span>
          <span class="required-mark">必填</span>
        </div>
        
        <el-form 
          ref="basicFormRef"
          :model="formData"
          :rules="basicFormRules"
          label-width="100px"
          label-position="left"
          class="basic-form"
        >
          <el-row :gutter="24">
            <!-- 客户编号 -->
            <el-col :span="12">
              <el-form-item label="客户编号">
                <el-input 
                  v-model="formData.customerCode" 
                  placeholder="系统自动生成"
                  disabled
                  class="disabled-input"
                >
                  <template #prefix>
                    <el-icon><Document /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 客户状态 -->
            <el-col :span="12">
              <el-form-item label="客户状态" prop="customerStatus">
                <el-select 
                  v-model="formData.customerStatus" 
                  placeholder="请选择客户状态"
                  class="full-width"
                >
                  <el-option label="有效客户" value="有效客户">
                    <span class="status-option">
                      <el-icon color="#34C759"><CircleCheck /></el-icon>
                      有效客户
                    </span>
                  </el-option>
                  <el-option label="潜在客户" value="潜在客户">
                    <span class="status-option">
                      <el-icon color="#007AFF"><User /></el-icon>
                      潜在客户
                    </span>
                  </el-option>
                  <el-option label="无效客户" value="无效客户">
                    <span class="status-option">
                      <el-icon color="#8E8E93"><Close /></el-icon>
                      无效客户
                    </span>
                  </el-option>
                  <el-option label="已成交客户" value="已成交客户">
                    <span class="status-option">
                      <el-icon color="#FF9500"><Star /></el-icon>
                      已成交客户
                    </span>
                  </el-option>
                  <el-option label="黑名单" value="黑名单">
                    <span class="status-option">
                      <el-icon color="#FF3B30"><WarningFilled /></el-icon>
                      黑名单
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 客户姓名 -->
            <el-col :span="12">
              <el-form-item label="客户姓名" prop="customerName">
                <el-input 
                  v-model="formData.customerName" 
                  placeholder="请输入客户真实姓名"
                  clearable
                  maxlength="10"
                  show-word-limit
                >
                  <template #prefix>
                    <el-icon><Avatar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 客户性别 -->
            <el-col :span="12">
              <el-form-item label="客户性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                  <el-radio value="男">男</el-radio>
                  <el-radio value="女">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <!-- 出生日期 -->
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker
                  v-model="formData.birthDate"
                  type="date"
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabledDate="disabledDate"
                  class="full-width"
                  @change="calculateAge"
                >
                  <template #prefix>
                    <el-icon><Calendar /></el-icon>
                  </template>
                </el-date-picker>
              </el-form-item>
            </el-col>

            <!-- 实际年龄 -->
            <el-col :span="12">
              <el-form-item label="实际年龄">
                <el-input 
                  :value="calculatedAge" 
                  placeholder="根据出生日期自动计算"
                  disabled
                  class="disabled-input"
                >
                  <template #suffix>
                    <span class="age-suffix">岁</span>
                  </template>
                  <template #prefix>
                    <el-icon><Clock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 身份证号 -->
            <el-col :span="24">
              <el-form-item label="身份证号" prop="idCard">
                <el-input 
                  v-model="formData.idCard" 
                  placeholder="请输入18位身份证号码"
                  maxlength="18"
                  show-word-limit
                  @blur="validateIdCard"
                >
                  <template #prefix>
                    <el-icon><CreditCard /></el-icon>
                  </template>
                  <template #suffix>
                    <el-icon 
                      v-if="idCardValidation.isValid" 
                      color="#34C759"
                    >
                      <CircleCheck />
                    </el-icon>
                    <el-tooltip 
                      v-else-if="idCardValidation.error"
                      :content="idCardValidation.error"
                      placement="top"
                    >
                      <el-icon color="#FF3B30">
                        <Warning />
                      </el-icon>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 联系方式信息区块 -->
      <div class="info-block">
        <div class="block-title">
          <el-icon><Phone /></el-icon>
          <span>联系方式信息</span>
          <span class="required-mark">部分必填</span>
        </div>
        
        <el-form 
          ref="contactFormRef"
          :model="contactInfo"
          :rules="contactFormRules"
          label-width="100px"
          label-position="left"
          class="contact-form"
        >
          <el-row :gutter="24">
            <!-- 主要手机 -->
            <el-col :span="12">
              <el-form-item label="主要手机" prop="primaryPhone">
                <el-input 
                  v-model="contactInfo.primaryPhone" 
                  placeholder="请输入11位手机号"
                  maxlength="11"
                  @blur="getPhoneLocation"
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                  <template #suffix>
                    <span v-if="phoneLocation" class="phone-location">
                      {{ phoneLocation }}
                    </span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 备用手机 -->
            <el-col :span="12">
              <el-form-item label="备用手机" prop="backupPhone">
                <el-input 
                  v-model="contactInfo.backupPhone" 
                  placeholder="请输入11位备用手机号"
                  maxlength="11"
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 微信号 -->
            <el-col :span="12">
              <el-form-item label="微信号">
                <el-input 
                  v-model="contactInfo.wechat" 
                  placeholder="请输入微信号"
                  maxlength="30"
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- QQ号 -->
            <el-col :span="12">
              <el-form-item label="QQ号">
                <el-input 
                  v-model="contactInfo.qq" 
                  placeholder="请输入QQ号"
                  maxlength="15"
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 电子邮箱 -->
            <el-col :span="24">
              <el-form-item label="电子邮箱" prop="email">
                <el-input 
                  v-model="contactInfo.email" 
                  placeholder="请输入电子邮箱地址"
                  type="email"
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 通讯地址 -->
            <el-col :span="18">
              <el-form-item label="通讯地址">
                <div class="address-input-group">
                  <el-cascader
                    v-model="contactInfo.addressRegion"
                    :options="regionOptions"
                    placeholder="请选择省市区"
                    clearable
                    class="region-selector"
                    @change="onRegionChange"
                  />
                  <el-input 
                    v-model="contactInfo.detailAddress" 
                    placeholder="请输入详细地址"
                    class="detail-address"
                  >
                    <template #prefix>
                      <el-icon><Location /></el-icon>
                    </template>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>

            <!-- 邮政编码 -->
            <el-col :span="6">
              <el-form-item label="邮政编码">
                <el-input 
                  v-model="contactInfo.postalCode" 
                  placeholder="邮政编码"
                  maxlength="6"
                >
                  <template #prefix>
                    <el-icon><Document /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 社会关系信息区块 -->
      <div class="info-block">
        <div class="block-title">
          <el-icon><UserFilled /></el-icon>
          <span>社会关系信息</span>
          <span class="required-mark">必填</span>
        </div>
        
        <el-form 
          ref="socialFormRef"
          :model="socialInfo"
          :rules="socialFormRules"
          label-width="120px"
          label-position="left"
          class="social-form"
        >
          <el-row :gutter="24">
            <!-- 紧急联系人姓名 -->
            <el-col :span="8">
              <el-form-item label="紧急联系人" prop="emergencyContactName">
                <el-input 
                  v-model="socialInfo.emergencyContactName" 
                  placeholder="请输入联系人姓名"
                  maxlength="10"
                >
                  <template #prefix>
                    <el-icon><Avatar /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 紧急联系人关系 -->
            <el-col :span="8">
              <el-form-item label="联系人关系" prop="emergencyContactRelation">
                <el-select 
                  v-model="socialInfo.emergencyContactRelation" 
                  placeholder="请选择关系"
                  class="full-width"
                >
                  <el-option label="配偶" value="配偶" />
                  <el-option label="子女" value="子女" />
                  <el-option label="亲属" value="亲属" />
                  <el-option label="朋友" value="朋友" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 紧急联系人电话 -->
            <el-col :span="8">
              <el-form-item label="联系人电话" prop="emergencyContactPhone">
                <el-input 
                  v-model="socialInfo.emergencyContactPhone" 
                  placeholder="请输入11位手机号"
                  maxlength="11"
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>

            <!-- 工作状态 -->
            <el-col :span="12">
              <el-form-item label="工作状态" prop="workStatus">
                <el-radio-group v-model="socialInfo.workStatus">
                  <el-radio value="在职">在职</el-radio>
                  <el-radio value="退休">退休</el-radio>
                  <el-radio value="待业">待业</el-radio>
                  <el-radio value="其他">其他</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <!-- 职业信息 -->
            <el-col :span="12">
              <el-form-item label="职业信息">
                <el-input 
                  v-model="socialInfo.occupation" 
                  placeholder="请输入职业信息"
                  maxlength="20"
                >
                  <template #prefix>
                    <el-icon><Briefcase /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { 
  User, CircleCheck, Warning, CreditCard, Document, Avatar, Male, Female, 
  Calendar, Clock, Phone, Message, Location, UserFilled, 
  Briefcase, Close, Star, WarningFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  formData: {
    type: Object,
    required: true
  },
  contactInfo: {
    type: Object,
    required: true
  },
  socialInfo: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['validation-change'])

// 表单引用
const basicFormRef = ref()
const contactFormRef = ref()
const socialFormRef = ref()

// 身份证验证状态
const idCardValidation = reactive({
  isValid: false,
  error: ''
})

// 手机号归属地
const phoneLocation = ref('')

// 计算的年龄
const calculatedAge = computed(() => {
  if (!props.formData.birthDate) return ''
  
  const today = new Date()
  const birthDate = new Date(props.formData.birthDate)
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  
  return age
})

// 表单验证规则
const basicFormRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2-10个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能包含中文字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择客户性别', trigger: 'change' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { len: 18, message: '身份证号必须为18位', trigger: 'blur' },
    { validator: validateIdCardNumber, trigger: 'blur' }
  ],
  customerStatus: [
    { required: true, message: '请选择客户状态', trigger: 'change' }
  ]
}

const contactFormRules = {
  primaryPhone: [
    { required: true, message: '请输入主要手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  backupPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const socialFormRules = {
  emergencyContactName: [
    { required: true, message: '请输入紧急联系人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2-10个字符', trigger: 'blur' }
  ],
  emergencyContactRelation: [
    { required: true, message: '请选择联系人关系', trigger: 'change' }
  ],
  emergencyContactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  workStatus: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ]
}

// 地区选项（简化版，实际应从接口获取）
const regionOptions = [
  {
    value: '110000',
    label: '北京市',
    children: [
      { value: '110100', label: '北京市' }
    ]
  },
  {
    value: '310000',
    label: '上海市', 
    children: [
      { value: '310100', label: '上海市' }
    ]
  }
  // 更多地区选项...
]

// 验证错误列表
const validationErrors = ref([])

// 是否有错误
const hasErrors = computed(() => validationErrors.value.length > 0)

// 完成度计算
const completionPercentage = computed(() => {
  const requiredFields = [
    props.formData.customerName,
    props.formData.gender,
    props.formData.birthDate,
    props.formData.idCard,
    props.formData.customerStatus,
    props.contactInfo.primaryPhone,
    props.socialInfo.emergencyContactName,
    props.socialInfo.emergencyContactRelation,
    props.socialInfo.emergencyContactPhone,
    props.socialInfo.workStatus
  ]
  
  const filledFields = requiredFields.filter(field => field && field.trim !== '').length
  return Math.round((filledFields / requiredFields.length) * 100)
})

// 日期禁用函数
const disabledDate = (time) => {
  // 禁用未来日期和过于久远的日期（120年前）
  const today = new Date()
  const minDate = new Date()
  minDate.setFullYear(today.getFullYear() - 120)
  
  return time.getTime() > today.getTime() || time.getTime() < minDate.getTime()
}

// 计算年龄
const calculateAge = () => {
  // 如果身份证号已填写且出生日期为空，从身份证号中提取出生日期
  if (props.formData.idCard && props.formData.idCard.length === 18 && !props.formData.birthDate) {
    const year = props.formData.idCard.substring(6, 10)
    const month = props.formData.idCard.substring(10, 12)
    const day = props.formData.idCard.substring(12, 14)
    
    if (year && month && day) {
      props.formData.birthDate = `${year}-${month}-${day}`
    }
  }
}

// 身份证验证
function validateIdCardNumber(rule, value, callback) {
  if (!value) {
    callback()
    return
  }
  
  // 基础格式检查
  if (!/^\d{17}[\dX]$/.test(value)) {
    idCardValidation.isValid = false
    idCardValidation.error = '身份证号格式不正确'
    callback(new Error('身份证号格式不正确'))
    return
  }
  
  // 校验码检查
  const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  
  let sum = 0
  for (let i = 0; i < 17; i++) {
    sum += parseInt(value[i]) * factors[i]
  }
  
  const remainder = sum % 11
  const expectedCheckCode = checkCodes[remainder]
  
  if (value[17] !== expectedCheckCode) {
    idCardValidation.isValid = false
    idCardValidation.error = '身份证号校验码不正确'
    callback(new Error('身份证号校验码不正确'))
    return
  }
  
  // 日期有效性检查
  const year = parseInt(value.substring(6, 10))
  const month = parseInt(value.substring(10, 12))
  const day = parseInt(value.substring(12, 14))
  
  const currentYear = new Date().getFullYear()
  if (year < 1900 || year > currentYear || month < 1 || month > 12 || day < 1 || day > 31) {
    idCardValidation.isValid = false
    idCardValidation.error = '身份证号中的日期不合法'
    callback(new Error('身份证号中的日期不合法'))
    return
  }
  
  idCardValidation.isValid = true
  idCardValidation.error = ''
  
  // 自动填入出生日期
  if (!props.formData.birthDate) {
    props.formData.birthDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
  }
  
  callback()
}

const validateIdCard = () => {
  if (basicFormRef.value) {
    basicFormRef.value.validateField('idCard')
  }
}

// 获取手机号归属地（模拟）
const getPhoneLocation = () => {
  if (props.contactInfo.primaryPhone && /^1[3-9]\d{9}$/.test(props.contactInfo.primaryPhone)) {
    // 这里应该调用实际的归属地查询API
    const prefixes = {
      '130': '河北', '131': '上海', '132': '北京', '133': '江苏',
      '134': '山东', '135': '广东', '136': '浙江', '137': '福建',
      '138': '湖南', '139': '四川'
    }
    
    const prefix = props.contactInfo.primaryPhone.substring(0, 3)
    phoneLocation.value = prefixes[prefix] || '未知'
  } else {
    phoneLocation.value = ''
  }
}

// 地区变化处理
const onRegionChange = (value) => {
  // 这里可以根据地区自动填入邮政编码
  if (value && value.length >= 2) {
    // 模拟邮政编码自动填入
    const postalCodes = {
      '110100': '100000', // 北京
      '310100': '200000'  // 上海
    }
    
    const code = value[value.length - 1]
    if (postalCodes[code]) {
      props.contactInfo.postalCode = postalCodes[code]
    }
  }
}

// 滚动到第一个错误
const scrollToFirstError = () => {
  nextTick(() => {
    const errorElement = document.querySelector('.el-form-item.is-error')
    if (errorElement) {
      errorElement.scrollIntoView({ 
        behavior: 'smooth', 
        block: 'center' 
      })
    }
  })
}

// 验证所有表单
const validateAllForms = async () => {
  const errors = []
  
  try {
    if (basicFormRef.value) {
      await basicFormRef.value.validate()
    }
  } catch (error) {
    errors.push(...Object.values(error))
  }
  
  try {
    if (contactFormRef.value) {
      await contactFormRef.value.validate()
    }
  } catch (error) {
    errors.push(...Object.values(error))
  }
  
  try {
    if (socialFormRef.value) {
      await socialFormRef.value.validate()
    }
  } catch (error) {
    errors.push(...Object.values(error))
  }
  
  validationErrors.value = errors
  
  emit('validation-change', {
    valid: errors.length === 0,
    errors: errors
  })
}

// 监听表单数据变化
watch([
  () => props.formData,
  () => props.contactInfo, 
  () => props.socialInfo
], () => {
  validateAllForms()
}, { deep: true })

// 生成客户编号
if (!props.formData.customerCode) {
  const now = new Date()
  const year = now.getFullYear()
  const timestamp = now.getTime().toString().slice(-6)
  props.formData.customerCode = `CRM${year}${timestamp}`
}
</script>

<style lang="scss" scoped>
.basic-info-section {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #E5E5EA;
    background: #FAFAFA;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .section-icon {
        font-size: 20px;
        color: #007AFF;
      }
      
      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #000000;
        margin: 0;
      }
    }
    
    .header-right {
      .el-button {
        font-size: 12px;
      }
    }
  }
  
  .section-content {
    padding: 24px;
  }
  
  .info-block {
    margin-bottom: 32px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .block-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 600;
      color: #3C3C43;
      
      .el-icon {
        font-size: 18px;
        color: #007AFF;
      }
      
      .required-mark {
        background: #FF3B30;
        color: white;
        font-size: 10px;
        padding: 2px 6px;
        border-radius: 4px;
        margin-left: auto;
      }
    }
  }
  
  .full-width {
    width: 100%;
  }
  
  .disabled-input {
    :deep(.el-input__inner) {
      background-color: #F2F2F7;
      color: #8E8E93;
    }
  }
  
  .status-option {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  
  .age-suffix {
    color: #8E8E93;
    font-size: 14px;
  }
  
  .phone-location {
    color: #8E8E93;
    font-size: 12px;
  }
  
  .address-input-group {
    display: flex;
    gap: 12px;
    width: 100%;
    
    .region-selector {
      width: 200px;
      flex-shrink: 0;
    }
    
    .detail-address {
      flex: 1;
    }
  }
  
}

// 响应式适配
@media (max-width: 768px) {
  .basic-info-section {
    .section-content {
      padding: 16px;
    }
    
    .address-input-group {
      flex-direction: column;
      
      .region-selector {
        width: 100%;
      }
    }
    
  }
}
</style>